from __future__ import absolute_import
from forest.api import Command, get_tool

import logging

logger = logging.getLogger('forest.commands.RootPassword')

Users = get_tool('users.Users')
class RootPassword(Command):
    ''' Sets the root password to the argument name password.

        An example to set the password to "root"::

            root_password: sha512 $6$Sa$kLSwlfbt9V2XhP3Tr/zRITF87xjRZep...<snip>

        .. describe:: root_password

            Password string. Either plaintext password, or a 2-part string,
            first word specifying the hash algorithm used to create
            the hash in the second word.

            You can generate a valid hash using the following one-liner::

                python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$SALT\$')"

            , replacing 'password' with the desired password, and entering any value of salt instead of SALT.

    '''
    __register__ = 'commands.setup.RootPassword'

    requires_config = ['root_password']

    def run(self, config):
        self.args = config.get('root_password', False)

        if not self.args:
            return

        #with get_tool('system.chroot')(config.get_install_root()):
        #if True:
            #runProcess('echo -e "password\password" | (passwd --stdin $USER)')
            #runProcess('(echo $PASSWORD | passwd --stdin root > /dev/null && echo) || echo "[FAIL]"')

        kwarg = {}

        arg_list = self.args.strip().split(' ')

        if len(arg_list) == 2:
            kwarg['algo'], pwd = arg_list
            kwarg['encrypted'] = True

        else :
            pwd = self.args.strip()


        users = Users(config.get_install_root())
        users.set_root_password(pwd, **kwarg)

            # passwdfile = open('/etc/passwd', 'rw').read()
            # shadowfile = open('/etc/passwd', 'rw').read()
            #
            # ## set up "install" user account
            # shadowfile+='\ninstall::14438:0:99999:7:::'
            # passwdfile+='\ninstall:x:0:0:root:/root:/sbin/loader'
            #
            # ## remove root password
            # shadowfile.replace('root:*:','root:%s:' % ('password'))
            #
            # get_tool('files.write')('/etc/passwd', passwdfile)
            #
            # get_tool('files.write')('/etc/shadow', shadowfile)

